package com.buydeem.share;

/**
 * 基础的生产者和消费者模型
 *
 * @author zengchao
 * @date 2021-07-21 14:36:36
 * @since 1.0
 */
public class WaitNotifyDemo7 {
    public static void main(String[] args) throws InterruptedException {
        Store2 store = new Store2(1, 0);

        Thread p1 = new Thread(() -> {
            while (true) {
                try {
                    store.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        p1.setName("p1");

        Thread p2 = new Thread(() -> {
            while (true) {
                try {
                    store.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        p2.setName("p2");

        Thread c1 = new Thread(() -> {
            while (true) {
                try {
                    store.remove();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        c1.setName("c1");

        Thread c2 = new Thread(() -> {
            while (true) {
                try {
                    store.remove();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        c2.setName("c2");

        p1.start();
        p2.start();
        c1.start();
        c2.start();

        p1.join();

    }
}

class Store2 {
    /**
     * 仓库的最大容量
     */
    private int maxCount;
    /**
     * 当前仓库的数量
     */
    private int currentCount;

    /**
     * 创建一个仓库
     *
     * @param maxCount     最大仓库容量
     * @param currentCount 初始化仓库数量
     */
    public Store2(int maxCount, int currentCount) {
        this.maxCount = maxCount;
        this.currentCount = currentCount;
    }

    /**
     * 存储产品
     */
    public synchronized void add() throws InterruptedException {
//        if (currentCount >= maxCount) {
//            wait();
//        }
        while (currentCount >= maxCount){
            wait();
        }
        System.out.printf("生产者[%s]:当前库存:[%d]，增加后的库存为:[%d]%n", Thread.currentThread().getName(), currentCount, ++currentCount);
        //notify();
        notifyAll();
    }

    /**
     * 消费产品
     */
    public synchronized void remove() throws InterruptedException {
//        if (currentCount <= 0) {
//            wait();
//        }
        while (currentCount <= 0){
            wait();
        }
        System.out.printf("消费者[%s]:当前库存:[%d]，减掉的库存为:[%d]%n", Thread.currentThread().getName(), currentCount, --currentCount);
//        notify();
        notifyAll();
    }
}